package com.ztom.daily.n2022.m5;

import java.util.ArrayList;
import java.util.List;

/**
 * 两棵二叉搜索树中的所有元素
 * <p>
 * https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees/
 *
 * @author ZhangTao
 */
public class Day01GetAllElements {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
        List<Integer> res = new ArrayList<>();

        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        inorder(root1, list1);
        inorder(root2, list2);

        // 归并
        int n1 = list1.size();
        int n2 = list2.size();
        int l = 0, r = 0;
        while (l < n1 && r < n2) {
            int val = list1.get(l) < list2.get(r) ? list1.get(l++) : list2.get(r++);
            res.add(val);
        }
        while (l < n1) {
            res.add(list1.get(l++));
        }
        while (r < n2) {
            res.add(list2.get(r++));
        }
        return res;
    }

    private void inorder(TreeNode node, List<Integer> list) {
        if (node == null) {
            return;
        }
        inorder(node.left, list);
        list.add(node.val);
        inorder(node.right, list);
    }
}
